const UserModel = require('../models/userModel.js');
const EnumModel = require('../models/enumModel.js');
const encryption = require('../utils/encryption.js');
const jwt = require('../utils/jwt.js');
const { isValidValue } = require('../utils');

const uModel = new UserModel();

exports.login = async ({ username, password }) => {
  const user = await UserModel.findByUsername(username);
  console.log('user', username, user);
  
  if (!isValidValue(user)) {
    throw new Error('用户不存在');
  }

  const userinfo = { ...user };
  delete userinfo.password;

  const isPasswordValid = await encryption.comparePassword(
    encryption.decryptAES(password), user.password);
  if (!isPasswordValid) {
    throw new Error('密码错误');
  }

  /**
   * 获取字典枚举
   */
  const enumType = await EnumModel.getAllEnumTypes() || [];
  const enumData = await EnumModel.getAllEnums() || [];

  /**
   * 生成token
   */
  const token = jwt.generateToken({ userId: user.id, username });

  return {
    token,
    userinfo,
    enumType,
    enumData
  }
};

exports.changePassword = async ctx => {
  const { userId, username, newPassword } = ctx;
  const user = await UserModel.findByUsername(username);
  if (!isValidValue(user)) {
    throw new Error('用户不存在');
  }
  const decryptAESPass = encryption.decryptAES(newPassword);
  const password = encryption.hashPassword(decryptAESPass);
  const { userinfo } = await uModel.updatePassword({ userId, password });

  if (userinfo && userinfo.id) return;
}